package com.czh.mock.providers.text.name;

import com.alibaba.fastjson.JSON;
import com.czh.mock.exceptions.FileException;
import com.czh.mock.exceptions.code.MockCodeEnum;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MockEnglishName {
    Logger logger = LoggerFactory.getLogger(MockEnglishName.class);
    private NameConfig config;
    private EnDataConfig dataConfig;

    private MockEnglishName(NameConfig config) {
        this.config = config;
    }

    public EnDataConfig getDataConfig() {
        if (this.dataConfig == null) {
            // 从json文件中
            try {
                this.dataConfig = JSON.parseObject(ClassLoader.getSystemResourceAsStream("config/name/en.json"), EnDataConfig.class);
            } catch (IOException e) {
                logger.error("读取中文名称数据配置文件失败：", e);
                throw new FileException(MockCodeEnum.READ_DATA_CONFIG_FILE);
            }
        }
        return dataConfig;
    }

    public void setDataConfig(EnDataConfig dataConfig) {
        this.dataConfig = dataConfig;
    }

    public static MockEnglishName build(NameConfig config) {
        return new MockEnglishName(config);
    }

    public String nextName() {
        List<String> nameWordList = new ArrayList<>();
        if (config.getSex() == null || !config.getSex()) {
            nameWordList.addAll(this.getDataConfig().getFirstMaleNames());
            nameWordList.addAll(this.getDataConfig().getFirstFemaleNames());
        } else {
            if (config.getMale() != null && config.getMale()) {
                nameWordList.addAll(this.getDataConfig().getFirstMaleNames());
            } else {
                nameWordList.addAll(this.getDataConfig().getFirstFemaleNames());
            }
        }
        return nameWordList.get(RandomUtils.nextInt(0, nameWordList.size())) + " " +
                this.getDataConfig().getLastNames().get(RandomUtils.nextInt(0, this.getDataConfig().getLastNames().size()));
    }
}
